package com.sg.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;


import com.alibaba.fastjson.JSONObject;

/**
 * 获取请求参数值
 * 
 * @author xzk
 * */
public class RequestBodyReadUtil {

	/**
	 * 根据request获取body字节流流数据，转换成字符输出，处理返回字符串
	 * 
	 * @param request
	 * @return String body字符串
	 * */
	public static String readRequestBody(HttpServletRequest request)
			throws Exception {
		//设置编码格式
		request.setCharacterEncoding("UTF-8");
		//获取请求中的数据流
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				request.getInputStream(), "UTF-8"));
		StringWriter writer = new StringWriter();
		String var2;
		try {
			//获取请求内容的mime-type
			String contentType = request.getContentType();
			write((Reader) reader, (Writer) writer);
			var2 = writer.getBuffer().toString();
			//进行转码
			if ("application/x-www-form-urlencoded".equals(contentType)) {
				var2 = URLDecoder.decode(var2, "utf-8");
			}
		} finally {
			writer.close();
		}

		return var2;
	}

	/**
	 * 根据request获取json格式body字节流流数据，转换成字符串，处理成json返回（适用于json嵌套请求数据）<br/>
	 * 如：{"param":{"username":"tom"}}
	 * 
	 * @param request
	 * @return JSONObject json格式
	 * */
	public static JSONObject readRequestBodyToJsonByKey(
			HttpServletRequest request, String key) throws Exception {
		JSONObject jsonObj = JSONObject.parseObject(readRequestBody(request));
		Object paramsObj = jsonObj.get(key);
		//判断值是否是字符类型，如果是字符类型则转换成jsonObject（适用于json嵌套请求数据）
		if (paramsObj instanceof String) {
			return JSONObject.parseObject(paramsObj.toString());
		}
		return jsonObj.getJSONObject(key);
	}
	
	/**
	 * 根据request获取json格式body字节流流数据，转换成字符串，处理成json返回
	 * 
	 * @param request
	 * @return JSONObject json格式
	 * */
	public static JSONObject readRequestBodyToJson(
			HttpServletRequest request) throws Exception {
		JSONObject jsonObj = JSONObject.parseObject(readRequestBody(request));;
		return jsonObj;
	}

	/**
	 *
	 * @param reader
	 * @param writer
	 * @return 字符串长度
	 * */
	public static long write(Reader reader, Writer writer) throws Exception {
		return write((Reader) reader, (Writer) writer, 8192);
	}

	/**
	 * 在获取字符串长度的同时将读入的字符，放入输入字符流中
	 * 
	 * @param reader
	 * @param writer
	 * @return 字符串长度
	 * */
	public static long write(Reader reader, Writer writer, int bufferSize)
			throws Exception {
		long total = 0L;

		int read;
		for (char[] buf = new char[8192]; (read = reader.read(buf)) != -1; total += (long) read) {
			writer.write(buf, 0, read);
		}

		return total;
	}
}
